import { Checkbox, Dropdown } from 'antd';
import { memo, useMemo, useState } from 'react';
import { Layout, useRefCallback } from '../../../util';
import { OrgTree as Tree } from '../../org-tree';

/**
 * 组织树
 * @param props
 * @constructor
 */
function OrgTree(props) {
  const params = useMemo(() => {
    return { containDept: false, dataAccessAuth: true, ...props.params };
  }, [props.params]);
  return <Tree defaultSelectedFirstNode  {...props} params={params} />;
}

/**
 * 用户帮助-公司
 * @param props
 * @returns
 */
function UserCompanyHelp(props) {
  const { multiple, borderStyle, treeProps, renderTable, getTable } = props;
  const [treeSelectedKeys, setTreeSelectedKeys] = useState<string[]>([]);

  // const onSelectCallback = useRefCallback((keys, nodes) => {
  //   getTable().setExtraParam({ treeNodes: nodes });
  // });

  const onControlledSelect = useRefCallback((keys, { selectedNodes }) => {
    const treeNodes = selectedNodes.filter((xt) => !treeSelectedKeys.includes(xt.key)) || [];
    const treeKeys = keys.filter((xt) => !treeSelectedKeys.includes(xt)) || [];
    getTable().setExtraParam({ treeNodes });
    setTreeSelectedKeys(treeKeys);
  });

  // 点击包含下级
  const onChangeIfNeedSub = useRefCallback((value) => {
    getTable().setExtraParam({
      containLowOrgUser: value
    });
  });

  // 目前需求是 用户帮助先试点 <包含下级> 功能
  // 如果后期各个帮助组件都需要此功能 建议写在 AsyncTree 组件统一参数控制
  const handleFilter = (DefaultCom) => {
    return (
      <>
        {DefaultCom}
        <Checkbox
          style={{ marginBottom: 5 }}
          onChange={(e) => {
            onChangeIfNeedSub(e.target.checked);
          }}
        >
          包含下级
        </Checkbox>
      </>
    );
  };

  return (
    <Layout.Flex direction="row" style={{ height: '100%' }}>
      <div style={{ width: 200, borderLeft: borderStyle, borderBottom: multiple ? 0 : borderStyle }}>
        <OrgTree
          {...treeProps}
          showFilter={handleFilter}
          selectedKeys={treeSelectedKeys}
          onSelect={onControlledSelect}
          titleRender={({ title, key }) => (
            <Dropdown
              disabled={!treeSelectedKeys.includes(key)}
              trigger={['contextMenu']}
              menu={{ items: [{ key: 'cancle', label: '取消选中' }] }}
              placement="top"
            >
              <span>{title}</span>
            </Dropdown>
          )}
          // 完全受控convertNode代替defaultSelectedFirstNode
          convertNode={(node, levelIndex) => {
            if (levelIndex.level === 0 && levelIndex.index === 0) {
              onControlledSelect([node.key], { selectedNodes: [node] });
            }
            return node;
          }}
        />
      </div>
      <Layout.Flex style={{ paddingBottom: multiple ? 32 : 0 }}>{renderTable(1)}</Layout.Flex>
    </Layout.Flex>
  );
}

export default memo(UserCompanyHelp);
